#include "timerf.h"

static TIMER  timerTcb[TIMERNUM];
static TIMER  *tmrList,*tmrFreeList;

void timer_list_init(void)
{
	u8   i;
	u32 xx;

	if(xx) {
		return;
	}
	
	for (i=0;i<TIMERNUM-1;i++) {
		timerTcb[i].tmr_next =&timerTcb[i+1];
		timerTcb[i].holdtime = 0x0;
		timerTcb[i].optime = 0x0;
		timerTcb[i].tmrfunc = NULL;
	}
	timerTcb[i].tmr_next =NULL;
	tmrFreeList = &timerTcb[0];
	tmrList =NULL;
}

TIMER *timer_create(void (*timerfunc)(void))
{
	TIMER *tmr;

	tmr = tmrFreeList;
	if (tmr != NULL) {
		__disable_irq();
		tmrFreeList = tmr->tmr_next;
		tmr->tmr_next = tmrList;
		tmrList = tmr;
		tmr->tmrfunc = timerfunc;
		tmr->holdtime = 0;
		__enable_irq();
	return tmr;
	} else {
		return NULL;
	}
}

void timer_start(TIMER *tmr,  u32 sec)
{
	if (tmr == NULL) return;
	if (tmrList == NULL) return;

	tmr->holdtime = sec*100;
	tmr->optime = tmr->holdtime;
}

void timer_stop(TIMER *tmr)
{
	if (tmr == NULL) return;
	if (tmrList == NULL) return;
	tmr->holdtime = 0;
	tmr->optime = 0;
}

u8 Timer_running(TIMER *tmr)
{
	if (tmr == NULL) return FALSE;
	if (tmrList == NULL) return FALSE;
	if (tmr->holdtime > 0) {
		return TRUE;
	} else {
		return FALSE;
	}   
}

void timer_remove(TIMER *pRemTimer)
{
    TIMER *pFront = NULL;
    TIMER *pCur   = NULL;
    
    if ( (tmrList != NULL) && (NULL == pRemTimer))
    {
        return;
    }

    pCur = pFront = tmrList;

    __disable_irq();
    if (pCur == pRemTimer)
    {
        tmrList = pCur->tmr_next;
        pCur->holdtime = 0;
        pCur->optime    = 0;
        pCur->tmrfunc   = NULL;
        pCur->tmr_next = tmrFreeList;
        tmrFreeList = pCur;
    }
    
    while(pFront->tmr_next != NULL)
    {
        pCur = pFront->tmr_next;

        if (pCur == pRemTimer)
        {
            pFront->tmr_next = pCur->tmr_next;

            pCur->holdtime = 0;
            pCur->optime    = 0;
            pCur->tmrfunc   = NULL;
            pCur->tmr_next = tmrFreeList;
            tmrFreeList = pCur;            
            break;
        }
        else
        {
            pFront = pCur;
        }
    }
    __enable_irq();

    
    return;
}

void vApplicationTickHook( void )
{
	TIMER  *tmr;
	void (*tmrfunc)(void);
	
	tmr = tmrList;
	while(tmr){
		if(tmr->holdtime>0){
			if (--tmr->optime == 0) {
				tmr->optime = tmr->holdtime;
				tmrfunc = tmr->tmrfunc;
				if(tmrfunc != NULL) (*tmrfunc)();
			}
		}
		tmr = tmr->tmr_next;
	}
}

